package com.liusy.code;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.internal.core.PackageFragment;
import org.eclipse.jdt.internal.core.PackageFragmentRoot;
import org.eclipse.jface.viewers.IStructuredSelection;

import com.liusy.code.bean.ClassNameInfo;
import com.liusy.code.bean.EntityFieldInfo;
import com.liusy.code.bean.JavaTemplateArgs;
import com.liusy.code.bean.JavaTemplateArgs.JavaTemplateType;
import com.liusy.code.bean.JspTemplateArgs;
import com.liusy.code.bean.JspTemplateArgs.JspTemplateType;
import com.liusy.code.bean.PackageNameInfo;
import com.liusy.code.bean.TableTemplateArgs;

/**
 * 工具类
 * 
 * @author liusy
 *
 */
@SuppressWarnings("restriction")
public class Tools
{
	
	public static Map<String,TableTemplateArgs> map = new HashMap<String, TableTemplateArgs>();
	/**
	 * 拷贝文件到项目中（用于搭建开发环境）
	 */
	public static void copyFileToProject(String source, String target) throws IOException
	{
		File sourceFile = new File(source);
		File targetFile = new File(target);

		if (sourceFile.isDirectory())
		{
			File[] files = sourceFile.listFiles();
			for (File file : files)
			{
				if (file.isDirectory())
				{
					FileUtils.copyDirectoryToDirectory(file, targetFile);
				} else
				{
					FileUtils.copyFileToDirectory(file, targetFile, true);
				}
			}
		} else
		{
			FileUtils.copyFileToDirectory(sourceFile, targetFile, true);
		}

	}

	/**
	 * 创建文件夹（用于jsp代码生成）
	 * @param path
	 */
	public static void createDirectory(String path)
	{
		File file = new File(path);
		//如果文件夹存在，则删除
		if (file.exists())
		{
			file.delete();
		}
		file.mkdirs();
	}

	/**
	 * 创建文件（用于jsp代码生成）
	 * @param path
	 * @return
	 */
	public static void createFile(String path)
	{
		File file = new File(path);
		if (file.exists())
		{
			file.delete();
		}
		try
		{
			file.createNewFile();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 往文件中写入字符串（用于jsp代码生成）
	 * @param filePath
	 * @param content
	 */
	public static void writeStringToFile(String filePath, String content)
	{
		File file = new File(filePath);
		try
		{
			FileUtils.writeStringToFile(file, content, "utf-8");
		} catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	@SuppressWarnings("unchecked")
	private static List<EntityFieldInfo> scanEntityField(ICompilationUnit compilationUnit)
	{
		List<EntityFieldInfo> entityFieldVos = new ArrayList<EntityFieldInfo>();
		//分析实体类的字段
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(compilationUnit);//设置资源
		parser.setResolveBindings(true);// 后面需要绑定
		CompilationUnit cu = (CompilationUnit) parser.createAST(null);

		List types = cu.types();
		TypeDeclaration typeDec = (TypeDeclaration) types.get(0);
		FieldDeclaration[] fieldDecs = typeDec.getFields();

		for (FieldDeclaration fieldDec : fieldDecs)
		{
			EntityFieldInfo entityFieldVo = new EntityFieldInfo();
			//字段类型
			entityFieldVo.setFieldType(fieldDec.getType().toString());
			for (Object fragment : fieldDec.fragments())
			{
				VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;
				//字段名称
				entityFieldVo.addFieldName(frag.getName().toString());
			}
			entityFieldVos.add(entityFieldVo);
		} 
		return entityFieldVos;
	}
	/**
	 * 生成java代码生成值对象
	 * @param selection
	 * @return
	 * @throws Exception 
	 */
	public static List<JavaTemplateArgs> createEntiryJavaTemplateArgsList(IStructuredSelection selection) throws Exception
	{
		map = new HashMap<String, TableTemplateArgs>();
		List<JavaTemplateArgs> javaTemplateArgsList = new ArrayList<JavaTemplateArgs>();
		Object obj = selection.getFirstElement();
		if (obj instanceof PackageFragment)
		{
			
			PackageFragment packageFragment = (PackageFragment) obj;
			PackageFragmentRoot pfrt = packageFragment.getPackageFragmentRoot();
			//获取包名对象
			PackageNameInfo packageNameInfo = new PackageNameInfo(packageFragment);

			
			DbHelp db = DbHelp.getDbHelp(Constant.driver,Constant.url,Constant.user,Constant.pwd);
			
			for(String tablename:Constant.tableNameTarget)
			{
				ClassNameInfo classNameInfo = new ClassNameInfo(tablename);
			
				JavaTemplateArgs j = new JavaTemplateArgs();
				j.setColumnInfoList(db.getColumnInfoList(tablename));
				j.setTableName(tablename);
				j.setPackageNameInfo(packageNameInfo);
				j.setClassNameInfo(classNameInfo);
				j.setType(JavaTemplateType.MODEL);
				map.put(classNameInfo.getEntityClassName(), j);
				javaTemplateArgsList.add(j);
			}
				
		}
		return javaTemplateArgsList;
	}
	
	
	/**
	 * 生成java代码生成值对象
	 * @param selection
	 * @return
	 * @throws Exception 
	 */
	public static List<JavaTemplateArgs> createJavaTemplateArgsList(IStructuredSelection selection) throws Exception
	{
		List<JavaTemplateArgs> javaTemplateArgsList = new ArrayList<JavaTemplateArgs>();
		Object obj = selection.getFirstElement();
		if (obj instanceof PackageFragment)
		{
			
			
			
			PackageFragment packageFragment = (PackageFragment) obj;
			PackageFragmentRoot pfrt = packageFragment.getPackageFragmentRoot();
			//获取包名对象
			PackageNameInfo packageNameInfo = new PackageNameInfo(packageFragment);
			IPackageFragment  p = pfrt.getPackageFragment(packageNameInfo.getEntityPackageName());
			
			//---------------------根据实体生成DAO、Servise、Action、JSP代码--------------------------
			
			ICompilationUnit[] compilationUnits = p.getCompilationUnits();
			//遍历实体类
			for (ICompilationUnit compilationUnit : compilationUnits)
			{
				//获取各个层的类名
				ClassNameInfo classNameInfo = new ClassNameInfo(compilationUnit);
				if(!map.containsKey(classNameInfo.getEntityClassName()))
					continue;
				//获取实体类属性
				List<EntityFieldInfo> entityFieldInfoList = scanEntityField(compilationUnit);
				//-------------------------------dao-------------------------------
				JavaTemplateArgs daoTemplateArgs = new JavaTemplateArgs();
				daoTemplateArgs.setPackageNameInfo(packageNameInfo);
				daoTemplateArgs.setClassNameInfo(classNameInfo);
				daoTemplateArgs.setEntityFieldInfoList(entityFieldInfoList);
				daoTemplateArgs.setType(JavaTemplateType.DAO);
				daoTemplateArgs.setColumnInfoList(map.get(classNameInfo.getEntityClassName()).getColumnInfoList());
				daoTemplateArgs.setTableName(map.get(classNameInfo.getEntityClassName()).getTableName());
				javaTemplateArgsList.add(daoTemplateArgs);
				//-------------------------------daoiml-------------------------------
				JavaTemplateArgs daoimlTemplateArgs = new JavaTemplateArgs();
				daoimlTemplateArgs.setPackageNameInfo(packageNameInfo);
				daoimlTemplateArgs.setClassNameInfo(classNameInfo);
				daoimlTemplateArgs.setEntityFieldInfoList(entityFieldInfoList);
				daoimlTemplateArgs.setType(JavaTemplateType.DAOIMPL);
				daoimlTemplateArgs.setColumnInfoList(map.get(classNameInfo.getEntityClassName()).getColumnInfoList());
				daoimlTemplateArgs.setTableName(map.get(classNameInfo.getEntityClassName()).getTableName());
				javaTemplateArgsList.add(daoimlTemplateArgs);
				//-------------------------------service-------------------------------
				JavaTemplateArgs serviceTemplateArgs = new JavaTemplateArgs();
				serviceTemplateArgs.setPackageNameInfo(packageNameInfo);
				serviceTemplateArgs.setClassNameInfo(classNameInfo);
				serviceTemplateArgs.setEntityFieldInfoList(entityFieldInfoList);
				serviceTemplateArgs.setType(JavaTemplateType.SERVICE);
				serviceTemplateArgs.setColumnInfoList(map.get(classNameInfo.getEntityClassName()).getColumnInfoList());
				serviceTemplateArgs.setTableName(map.get(classNameInfo.getEntityClassName()).getTableName());
				javaTemplateArgsList.add(serviceTemplateArgs);
				//-------------------------------serviceiml-------------------------------
				JavaTemplateArgs serviceImplTemplateArgs = new JavaTemplateArgs();
				serviceImplTemplateArgs.setPackageNameInfo(packageNameInfo);
				serviceImplTemplateArgs.setClassNameInfo(classNameInfo);
				serviceImplTemplateArgs.setEntityFieldInfoList(entityFieldInfoList);
				serviceImplTemplateArgs.setType(JavaTemplateType.SERVICEIMPL);
				serviceImplTemplateArgs.setColumnInfoList(map.get(classNameInfo.getEntityClassName()).getColumnInfoList());
				serviceImplTemplateArgs.setTableName(map.get(classNameInfo.getEntityClassName()).getTableName());
				javaTemplateArgsList.add(serviceImplTemplateArgs);
				//-------------------------------action-------------------------------
				JavaTemplateArgs actionTemplateArgs = new JavaTemplateArgs();
				actionTemplateArgs.setPackageNameInfo(packageNameInfo);
				actionTemplateArgs.setClassNameInfo(classNameInfo);
				actionTemplateArgs.setEntityFieldInfoList(entityFieldInfoList);
				actionTemplateArgs.setType(JavaTemplateType.ACTION);
				actionTemplateArgs.setColumnInfoList(map.get(classNameInfo.getEntityClassName()).getColumnInfoList());
				actionTemplateArgs.setTableName(map.get(classNameInfo.getEntityClassName()).getTableName());
				javaTemplateArgsList.add(actionTemplateArgs);
			}
		}
		return javaTemplateArgsList;
	}

	/**
	 * 生成jsp代码生成值对象
	 * @param selection
	 * @return
	 * @throws Exception 
	 */
	public static List<JspTemplateArgs> createJspTemplateArgsList(IStructuredSelection selection) throws Exception
	{
		List<JspTemplateArgs> jspTemplateArgsList = new ArrayList<JspTemplateArgs>();

		Object obj = selection.getFirstElement();
		if (obj instanceof PackageFragment)
		{
			PackageFragment packageFragment = (PackageFragment) obj;
			PackageFragmentRoot pfrt = packageFragment.getPackageFragmentRoot();
			//获取包名对象
			PackageNameInfo packageNameInfo = new PackageNameInfo(packageFragment);
			IPackageFragment  p = pfrt.getPackageFragment(packageNameInfo.getEntityPackageName());
			
			
			ICompilationUnit[] compilationUnits = p.getCompilationUnits();
			//遍历实体类
			for (ICompilationUnit compilationUnit : compilationUnits)
			{
				//获取各个层的类名
				ClassNameInfo classNameInfo = new ClassNameInfo(compilationUnit);
				if(!map.containsKey(classNameInfo.getEntityClassName()))
					continue;
				//获取实体类属性
				List<EntityFieldInfo> entityFieldInfoList = scanEntityField(compilationUnit);
				//-------------------------------list-------------------------------
				JspTemplateArgs JspListTemplateArgs = new JspTemplateArgs();
				JspListTemplateArgs.setPackageNameInfo(packageNameInfo);
				JspListTemplateArgs.setEntityName(classNameInfo.getEntityClassName());
				JspListTemplateArgs.setClassNameInfo(classNameInfo);
				JspListTemplateArgs.setEntityFieldInfoList(entityFieldInfoList);
				JspListTemplateArgs.setType(JspTemplateType.LIST);
				JspListTemplateArgs.setColumnInfoList(map.get(classNameInfo.getEntityClassName()).getColumnInfoList());
				JspListTemplateArgs.setTableName(map.get(classNameInfo.getEntityClassName()).getTableName());
				jspTemplateArgsList.add(JspListTemplateArgs);
				//-------------------------------input-------------------------------
				JspTemplateArgs JspFormTemplateArgs = new JspTemplateArgs();
				JspFormTemplateArgs.setPackageNameInfo(packageNameInfo);
				JspFormTemplateArgs.setEntityName(classNameInfo.getEntityClassName());
				JspFormTemplateArgs.setClassNameInfo(classNameInfo);
				JspFormTemplateArgs.setEntityFieldInfoList(entityFieldInfoList);
				JspFormTemplateArgs.setType(JspTemplateType.FORM);
				JspFormTemplateArgs.setColumnInfoList(map.get(classNameInfo.getEntityClassName()).getColumnInfoList());
				JspFormTemplateArgs.setTableName(map.get(classNameInfo.getEntityClassName()).getTableName());
				jspTemplateArgsList.add(JspFormTemplateArgs);
				//-------------------------------input-------------------------------
				JspTemplateArgs JspAddTemplateArgs = new JspTemplateArgs();
				JspAddTemplateArgs.setPackageNameInfo(packageNameInfo);
				JspAddTemplateArgs.setEntityName(classNameInfo.getEntityClassName());
				JspAddTemplateArgs.setClassNameInfo(classNameInfo);
				JspAddTemplateArgs.setEntityFieldInfoList(entityFieldInfoList);
				JspAddTemplateArgs.setType(JspTemplateType.ADD);
				JspAddTemplateArgs.setColumnInfoList(map.get(classNameInfo.getEntityClassName()).getColumnInfoList());
				JspAddTemplateArgs.setTableName(map.get(classNameInfo.getEntityClassName()).getTableName());
				jspTemplateArgsList.add(JspAddTemplateArgs);
			}
			
		}
		return jspTemplateArgsList;
	}

	
	public static String toFirstUpperCase(String name)
	{
		String namel = name.toLowerCase();
		String [] names = namel.split("_");
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i<names.length;i++)
		{
			sb.append(Character.toUpperCase(names[i].charAt(0))).append(names[i].substring(1)).toString();
		}
		return sb.toString();
	}
	public static String toFirstLowerCase(String name)
	{
		String namel = name.toLowerCase();
		String [] names = namel.split("_");
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i<names.length;i++)
		{
			if(i==0)
			sb.append(Character.toLowerCase(names[i].charAt(0))).append(names[i].substring(1)).toString();
			else
				sb.append(Character.toUpperCase(names[i].charAt(0))).append(names[i].substring(1)).toString();
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		System.out.println( toFirstUpperCase("liushneyge"));
		System.out.println( toFirstUpperCase("LIU_shengye"));
		
		System.out.println( toFirstLowerCase("PINGTAISHENQING_ID"));
		
		System.out.println( StringUtils.uncapitalize("LiuShengye"));
	}
}
